package cn.ex.basic.controller;

import cn.ex.basic.customexception.BusinessException;
import cn.ex.basic.util.AjaxResult;
import cn.ex.basic.util.FastdfsUtil;
import cn.ex.org.service.IShopService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * @Author: ZeWangmu
 * @Date: 2022/06/12/21:13
 * @Description: 用于logo上传和删除的分布式接口
 */
@RestController
@RequestMapping("/fastDfs")
public class FastDfsController {

    /**
     * 上传logo
     */
    @PostMapping("/upload")
    public AjaxResult upload(@RequestPart(value = "file",required = true)MultipartFile file){
        try {
            //获取上传时的文件名
            String filename = file.getOriginalFilename();
            //截取文件的后缀(eg:jpg)
            String extName = filename.substring(filename.lastIndexOf(".")+1);
            String path = FastdfsUtil.upload(file.getBytes(),extName);
            return AjaxResult.me().setResultObj(path);
        } catch (BusinessException e) {
            //将异常信息返回给后台
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("保存对象失败！"+e.getMessage());
        }
    }

    /**
     * 删除logo
     */
    @DeleteMapping
    public AjaxResult delete(@RequestParam String path){
        try {
            //截取第一个/后的子串
            String pathTem = path.substring(1);
            //截取组名
            String groupName = pathTem.substring(0, pathTem.indexOf("/"));
            //截取获得文件名
            String fileName = pathTem.substring(pathTem.indexOf(pathTem.indexOf("/") + 1));
            FastdfsUtil.delete(groupName,fileName);
            return AjaxResult.me();
        } catch (BusinessException e) {
            //将异常信息返回给后台
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("系统繁忙，请稍后重试！！！"+e.getMessage());
        }
    }

}
